from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from accounts.models import StudentSurvey
from accounts.utils.data_analysis import SurveyAnalyzer
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from pyecharts.charts import Radar, Bar, Line, Scatter, Pie
import json
from django.db.models import Count
# 为了向后兼容，保留函数式视图但重定向到类视图


class DashboardView(TemplateView):
    template_name = 'index.html'

    def __init__(self):
        self.model = StudentSurvey

    def get_user_count(self):
        # 从数据库获取所有调查数据
        surveys = self.model.objects.all()
        # 获取总人数
        total_count = surveys.count()
        # 获取女性人数
        female_count = surveys.filter(gender='F').count()
        # 获取男性人数
        male_count = surveys.filter(gender='M').count()
        return total_count, female_count, male_count

    def get_sports_activities(self):
        # 从数据库获取所有调查数据
        surveys = self.model.objects.all()

        # 按性别分组的调查数据
        male_surveys = surveys.filter(gender='M')
        female_surveys = surveys.filter(gender='F')

        # 定义所有活动项目字段
        # , 'sports', 'dance', 'band','marching', 'music', 'rock'
        activity_fields = [
            'basketball', 'football', 'soccer', 'softball', 'volleyball',
            'swimming', 'baseball', 'tennis'
        ]

        # 添加对应的中文名称
        # '体育运动', '舞蹈', '乐队', '军乐队', '音乐', '摇滚音乐'
        activity_names = [
            '篮球', '足球', '英式足球', '垒球', '排球',
            '游泳', '棒球', '网球',
        ]

        # 统计每个活动项目的参与人次（兴趣度>0表示参与）
        male_counts = []
        female_counts = []
        all_counts = []

        for i, field in enumerate(activity_fields):
            # 计算全量的参与人次
            total_participants = 0
            for survey in surveys:
                if getattr(survey, field, 0) > 0:
                    total_participants += 1
            all_counts.append(total_participants)

            # # 计算男性参与人次
            # male_participants = 0
            # for survey in male_surveys:
            #     if getattr(survey, field, 0) > 0:
            #         male_participants += 1
            # male_counts.append(male_participants)

            # # 计算女性参与人次
            # male_participants = 0
            # for survey in female_surveys:
            #     if getattr(survey, field, 0) > 0:
            #         male_participants += 1
            # female_counts.append(male_participants)

        # 创建柱状图
        # activity_bar = (
        #     Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width='100%', height='300px'))
        #     .add_xaxis(activity_names)
        #     .add_yaxis(
        #         "女生参与人次",
        #         female_counts,
        #         category_gap="50%",
        #         gap="0%",
        #         stack="stack1",
        #         itemstyle_opts=opts.ItemStyleOpts(
        #             color="#91cc75",
        #             border_radius=[0, 0, 0, 0]
        #         )
        #     )
        #     .add_yaxis(
        #         "男生参与人次",
        #         male_counts,
        #         category_gap="50%",
        #         gap="0%",
        #         stack="stack1",
        #         itemstyle_opts=opts.ItemStyleOpts(
        #             color="#5470c6",
        #             border_radius=[7, 7, 0, 0]
        #         )
        #     )
        #     .set_global_opts(
        #         title_opts=opts.TitleOpts(title="各体育项目性别参与人次分布"),
        #         xaxis_opts=opts.AxisOpts(name="体育项目", axislabel_opts=opts.LabelOpts(rotate=30)),
        #         yaxis_opts=opts.AxisOpts(name="参与人次"),
        #         legend_opts=opts.LegendOpts(pos_top="5%"),
        #         tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="shadow")
        #     )
        #     .set_series_opts(
        #         label_opts=opts.LabelOpts(is_show=True, position="inside")
        #     )
        # )

        return all_counts, activity_names  # activity_bar.render_embed()

    # 获取各个兴趣点男性和女性分布的柱状图
    def get_interest_distribution(self):
        """获取各个兴趣类别男性和女性分布的柱状图"""
        surveys = self.model.objects.all()
        male_surveys = surveys.filter(gender='M')
        female_surveys = surveys.filter(gender='F')

        # 定义要分析的兴趣类别
        interest_categories = [
            ['体育活动', ['basketball', 'football', 'soccer', 'softball', 'volleyball', 'swimming', 'baseball', 'tennis', 'sports']],
            ['艺术音乐', ['dance', 'band', 'marching', 'music', 'rock']],
            ['宗教活动', ['god', 'church', 'jesus', 'bible']],
            ['时尚购物', ['hair', 'dress', 'mall', 'shopping', 'clothes', 'hollister', 'abercrombie']],
            ['个性特征', ['cute', 'sexy', 'hot', 'kissed']],
            ['风险行为', ['drunk', 'drugs', 'death', 'die']]
        ]

        category_names = [category[0] for category in interest_categories]
        all_count = []
        all_count_bar = []
        all_male_count = []
        all_female_count = []

        print('category_names', category_names)

        # 计算每个兴趣类别的男女参与人数
        for category, fields in interest_categories:
            # 计算总参与人次
            total_participants = 0
            for survey in surveys:
                for field in fields:
                    if getattr(survey, field, 0) > 0:
                        total_participants += 1
                        break
            all_count.append(total_participants)
            all_count_bar.append({'count': total_participants})
            # 计算男性参与人次
            male_participants = 0
            for survey in male_surveys:
                for field in fields:
                    if getattr(survey, field, 0) > 0:
                        male_participants += 1
                        break
            all_male_count.append({'count': male_participants})
            # 计算女性参与人次
            female_participants = 0
            for survey in female_surveys:
                for field in fields:
                    if getattr(survey, field, 0) > 0:
                        female_participants += 1
                        break
            all_female_count.append({'count': female_participants})
        # 创建柱状图
        interest_bar_data = []

        for i, category in enumerate(category_names):
            interest_bar_data.append({
                'name': category,
                'value': all_count[i]
            })

        return interest_bar_data, all_count_bar, all_male_count, all_female_count, category_names

    def get_graduation_year_distribution(self):
        surveys = self.model.objects.all()

        # 获取所有毕业年份并按年份分组统计
        grad_years = surveys.values('gradyear').annotate(count=Count('gradyear')).order_by('gradyear')

        # 提取数据
        graduation_years = [item['gradyear'] for item in grad_years]
        graduation_year_counts = [item['count'] for item in grad_years]
        return graduation_years, graduation_year_counts

    def get_religion_bar_data(self):
        surveys = self.model.objects.all()
        analyzer = SurveyAnalyzer()
        religions = analyzer.analyze_religions()
        religion_bar_data1 = religions['religion_dist']
        religion_bar_keys = [k.replace('dist_', '') for k in religion_bar_data1.keys()]
        print(religion_bar_keys, religion_bar_data1)
        religion_bar_data = []

        religion_bar_value = []

        for i, key in enumerate(religion_bar_keys):
            religion_bar_value.append({
                'name': key,
                'count': religion_bar_data1.get('dist_' + key, 0)
            })
        # for  in religion_bar_keys:
        return religion_bar_value

    def get_context_data(self, **kwargs):
        # 获取总人数、女性人数、男性人数
        total_count, female_count, male_count = self.get_user_count()
        context = super().get_context_data(**kwargs)
        context['total_count'] = total_count
        context['female_count'] = female_count
        context['male_count'] = male_count
        interest_bar_data, all_count_bar, all_male_count, all_female_count, category_names = self.get_interest_distribution()
        context['interest_bar_data'] = interest_bar_data
        context['all_count_bar'] = all_count_bar
        context['all_male_count'] = all_male_count
        context['all_female_count'] = all_female_count
        context['category_names'] = category_names

        print('all_count_bar', category_names)

        all_counts, activity_names = self.get_sports_activities()
        context['all_counts'] = all_counts
        context['activity_names'] = activity_names

        graduation_years, graduation_year_counts = self.get_graduation_year_distribution()
        context['graduation_years'] = graduation_years
        context['graduation_year_counts'] = graduation_year_counts

        religion_bar_value = self.get_religion_bar_data()
        context['religion_bar_value'] = religion_bar_value
        return context
